package com.zl_huang.example.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.zl_huang.example.model.User;
import com.zl_huang.example.model.UserRole;
import com.zl_huang.example.service.IUserRoleService;

public class LoginInterceptor implements HandlerInterceptor {
	@Autowired
	private IUserRoleService userRoleService;

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception e)
			throws Exception {
		System.out.println("-----------------LoginInterceptor.afterCompletion---------------------------------");

	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView modelAndeView)
			throws Exception {
		System.out.println("-----------------LoginInterceptor.postHandle---------------------------------");

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		
		if(user != null){
			UserRole userRole = userRoleService.getUserRoleById(user.getUser_id());						
			if(userRole != null){
				session.setAttribute("role", userRole.getRole().getRole_id());
			}
			return true;
		}else{
			response.sendRedirect(request.getContextPath()+"/login");
		}
		System.out.println("------------------------LoginInterceptor.preHandle----------------------------");
		return false;
	}

}
